//
//  ZREmoticonView.swift
//  Sina
//
//  Created by 张锐 on 16/3/8.
//  Copyright © 2016年 zhangr. All rights reserved.
//

import UIKit

let ZREmoticonViewReuseIdentifier = "ZREmoticonViewReuseIdentifier"

class ZREmoticonView: UIView ,UICollectionViewDataSource,ZREmoticonBarDelegate{

   //构造函数
   override init(frame: CGRect) {
        super.init(frame: frame)
    
        setupUI()
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    //setupUI
    private func setupUI(){
        
        
    
        addSubview(emoticonCollectionView)
        
        addSubview(emoticonBar)
        
        emoticonBar.delegate = self
        
        emoticonBar.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(self.snp_left)
            
            make.right.equalTo(self.snp_right)
            
            make.bottom.equalTo(self.snp_bottom)
            
            make.height.equalTo(44)
        }
        
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(self.snp_left)
            
            make.right.equalTo(self.snp_right)
            
            make.top.equalTo(self.snp_top)
            
            make.bottom.equalTo(emoticonBar.snp_top)
        }
        
        emoticonCollectionView.dataSource = self
        
        emoticonCollectionView.registerClass(ZREmoticonCollectionViewCell.self, forCellWithReuseIdentifier: ZREmoticonViewReuseIdentifier)
        
        emoticonCollectionView.pagingEnabled = true
        
        emoticonCollectionView.showsHorizontalScrollIndicator = false
        
        emoticonCollectionView.showsVerticalScrollIndicator = false
        
        emoticonCollectionView.bounces = false
        
    
    }
    //懒加载
    var flowLayout : UICollectionViewFlowLayout = {
        
        let flowLayout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width, 172)
        
        flowLayout.minimumInteritemSpacing = 0
        
        flowLayout.minimumLineSpacing = 0
        
        flowLayout.scrollDirection = .Horizontal
        
        return flowLayout
        
    }()
    
    lazy var emoticonCollectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)
    
    lazy var emoticonBar : ZREmoticonBar = ZREmoticonBar()
    
    
}
// MARK: - collectionView代理方法
extension ZREmoticonView{

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return ZREmoticonManger.getAllEmoticons().count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return ZREmoticonManger.getAllEmoticons()[section].count
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell  = collectionView.dequeueReusableCellWithReuseIdentifier(ZREmoticonViewReuseIdentifier, forIndexPath: indexPath) as! ZREmoticonCollectionViewCell
        
        cell.backgroundColor = UIColor.orangeColor()
        
//        cell.message = "\(indexPath.section)  \(indexPath.item)"
        
        cell.emoticons = ZREmoticonManger.getAllEmoticons()[indexPath.section][indexPath.item]
        
        return cell
        
    }

}

class ZREmoticonCollectionViewCell : UICollectionViewCell {
    
//    var message : String?{
//    
//        didSet{
//        
//            messageLabel.text = message
//        
//        }
//    
//    
//    }
    
    var emoticons : [ZREmoticonModel]?{
    
        didSet{
            //防止重用
            for i in 0..<20{
            
                buttons[i].hidden = true
                
            }
            
            for (index,emoticon) in (emoticons?.enumerate())!{
                
                
                if let png = emoticon.png {
                    
                    let button = buttons[index]
                    
                    button.emoticon = emoticon
                    
                    button.hidden = false
                    
                    button.setImage(UIImage(named: "\(emoticon.packagePath!)/\(png)"), forState: UIControlState.Normal)
                    
                    button.setTitle("", forState: UIControlState.Normal)
                    
                }
                
                if let emoji = emoticon.emoji{
                    
                    let button = buttons[index]
                    
                    button.emoticon = emoticon
                    
                    button.hidden = false
                    
                    button.setImage(nil, forState: UIControlState.Normal)
                    
                    button.setTitle("\(emoji)", forState: UIControlState.Normal)
                    
                    button.titleLabel?.font = UIFont.systemFontOfSize(32)
                    
                    
                }
                
                
            }
            
        }
        
    }
    
    //构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //setupUI
    func setupUI(){
        
        //
//        addSubview(messageLabel)
//        
//        messageLabel.snp_makeConstraints { (make) -> Void in
//            
//            make.center.equalTo(snp_center)
//        }
        
        
        //添加按钮
        setupBtns()
        
        //添加删除按钮
        addSubview(deleteButton)
        
        deleteButton.frame = CGRectMake(6.0 * self.frame.width / 7, 2.0 * self.frame.height / 3, self.frame.width / 7, self.frame.height / 3)
    
    }
    
    
    /**
     添加表情按钮
     */
    private func setupBtns(){
        
        let buttonW = self.frame.width / 7
        
        let buttonH = self.frame.height / 3
        
        for i in 0..<20{
            
            let button = ZREmoticonButton(type: UIButtonType.Custom)
            
            button.frame = CGRectMake(CGFloat(i % 7) * buttonW, CGFloat(i / 7) * buttonH, buttonW, buttonH)
            
            button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            contentView.addSubview(button)
            
            buttons.append(button)
            
        }

    }
    /**
     表情按钮点击事件
     */
    func emoticonButtonClick(emoticonButton : ZREmoticonButton){
//    添加到最近使用表情
        ZREmoticonManger.addRecentEmoticon(emoticonButton.emoticon!)
//    表情上屏,发送通知
        NSNotificationCenter.defaultCenter().postNotificationName("emoticonButtonClickNotification", object: nil, userInfo: ["emoticon" : emoticonButton.emoticon!])
    
    }
    //懒加载
    private lazy var buttons : [ZREmoticonButton] = [ZREmoticonButton]()
    
//    private lazy var messageLabel : UILabel = UILabel()
    
    private lazy var deleteButton : UIButton = {
    
        let deleteButton = UIButton(type: UIButtonType.Custom)
        
        deleteButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Normal)
        
        deleteButton.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
    
        return deleteButton
    }()
    /**
     删除按钮点击事件
     */
    func deleteButtonClick(){
    
        print("删除按钮点击了")
    
    }

}

// MARK: - emoticonBarDelegate
extension ZREmoticonView{

    /**
     代理方法实现滚到相应组
     */
    func emoticonBarButtonClick(button : UIButton) {
        
        
        let indexPath = NSIndexPath(forItem: 0, inSection: button.tag)
        
        emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .None, animated: false)
        
    }

}